package com.cash.loan.common.submessage;

import com.alibaba.fastjson.JSONObject;
import com.cash.loan.config.properties.NewMessageProperties;
import com.cash.loan.config.properties.SubMailProperties;
import com.submail.lib.MESSAGEXsend;
import com.submail.utils.AppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Administrator
 * @decription 短信发送
 * @Date 2018-02-02 10:11
 */
@Component
public class MessageService {

    private static Logger logger = LoggerFactory.getLogger(MessageService.class);

    /**
     * submail
     */
    @Autowired
    private SubMailProperties subMailProperties;

    /**
     * 新的短信服务(保留测试)
     */
    @Autowired
    private NewMessageProperties messageProperties;

    private static final String SUCCESS_STATUS = "success";

    /**
     * 短信发送
     * @param phone
     * @param code
     * @return
     */
    public Boolean sendMessage(String phone, String code) {

        AppConfig appConfig = new AppConfig();
        appConfig.setAppId(subMailProperties.getAppId());
        appConfig.setAppKey(subMailProperties.getAppKey());
        MESSAGEXsend messageXsend = new MESSAGEXsend(appConfig);

        messageXsend.addTo(phone);
        messageXsend.setProject(subMailProperties.getProjectName());
        messageXsend.addVar("code",code);
        String result = messageXsend.xsend();
        JSONObject jsonObject = JSONObject.parseObject(result);
        String status = (String) jsonObject.get("status");
        if(SUCCESS_STATUS.equals(status)) {
            return true;
        } else {
            logger.error("sendMessage(): 短信发送失败");
            return false;
        }
    }

    /**
     * 新的短信三方
     * @param phone
     * @param code
     * @return
     */
    public Boolean sendNewMessage(String phone, String code) {
        StringBuffer params = new StringBuffer();
        try {
            params.append("userid=").append(messageProperties.getUserId())
                    .append("&username=").append(messageProperties.getUserName())
                    .append("&passwordMd5=").append(messageProperties.getPassword())
                    .append("&mobile=").append(phone)
                    .append("&message=").append(java.net.URLEncoder.encode(messageProperties.getMessageContent() + code, "GBK"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String result = httpPostRequest(messageProperties.getUrl(), params.toString(), "GBK");
        String res = result.split("\r\n")[0].trim();
        String temp = "";
        if(res.length() > 4) {
            temp = res.substring(0,4).trim();
        } else {
            temp = res;
        }
        int intRes = Integer.parseInt(temp);
        if(intRes < 0) {
            logger.error("短信发送平台发生错误："+result.split("\r\n")[1] + ",错误码：" + intRes);
            return false;
        } else {
            return true;
        }
    }

    /**
     * 短信发送http请求
     * @param urlStr
     * @param params
     * @param charset
     * @return
     */
    private String httpPostRequest(String urlStr,  String params, String charset){
        try {
            byte[] data = params.getBytes(charset);
            URL url =new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset="+ charset);
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));

            OutputStream outStream = conn.getOutputStream();
            outStream.write(data);
            outStream.flush();
            outStream.close();

            int responseCode = conn.getResponseCode();
            if(responseCode == 200){
                InputStream is = conn.getInputStream();
                StringBuffer sb = new StringBuffer();
                int nRead;
                byte[] bBuffer = new byte[1024];
                do {
                    nRead = is.read(bBuffer);
                    if (nRead <= 0) {
                        break;
                    }
                    sb.append(new String(bBuffer, 0, nRead, charset));
                } while (true);

                return sb.toString();
            }
            return Integer.toString(responseCode);
        } catch (Exception e) {
            logger.error("http get error:" + urlStr + ".http request error:" + e.getMessage());
            return "9999";
        }
    }
}
